package com.gao.modules.depart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gao.base.Result;
import com.gao.modules.depart.mapper.SysDepartMapper;
import com.gao.modules.depart.pojo.SysDepart;
import com.gao.modules.depart.service.SysDepartService;
import com.gao.modules.userdepart.pojo.SysUserDepart;
import com.gao.modules.userdepart.service.SysUserDepartService;
import com.gao.utils.MyBatisPlusUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SysDepartServiceImpl extends ServiceImpl<SysDepartMapper, SysDepart> implements SysDepartService {

    @Resource
    private SysDepartMapper sysDepartMapper;

    @Autowired
    private SysUserDepartService sysUserDepartService;

    @Override
    @Transactional
    public Result insert(SysDepart sysDepart,SysDepart parentDepart) {
        SysDepart existDepart = sysDepartMapper.selectOne(new QueryWrapper<SysDepart>().eq("depart_name", sysDepart.getDepartName()));
        if(existDepart.getDepartName().equals(sysDepart.getDepartName())){
            return Result.error("已有该部门，请重新输入部门名称");
        }else {
            StringBuffer rawParentIds = new StringBuffer();
            StringBuffer rawChildrenIds = new StringBuffer();
            if (parentDepart.getId().equals("0") ){
                rawParentIds.append(parentDepart.getId());
            }else {
                rawParentIds.append(parentDepart.getParentIds()).append(",").append(parentDepart.getId());
            }
            if(parentDepart.getChildrenIds() == null){
                rawParentIds.append(sysDepart.getId());
            }else {
                rawChildrenIds.append(parentDepart.getChildrenIds()).append(",").append(sysDepart.getId());
            }
            sysDepart.setParentIds(rawParentIds.toString());
            sysDepart.setLevel(parentDepart.getLevel() + 1);
            this.save(sysDepart);
            parentDepart.setChildrenIds(rawChildrenIds.toString());
            this.updateById(parentDepart);
            return Result.success();
        }
    }

    @Override
    public List<SysDepart> queryDepartsByWant(SysDepart sysDepart) {
        QueryWrapper<SysDepart> queryWrapper = MyBatisPlusUtil.getQueryWrapper(sysDepart);
        //返回List之类的类型时候最好排序一下
        queryWrapper.orderByDesc("create_time");
        return sysDepartMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional
    public Result delete(String departId) {
        SysDepart executedDepart = this.getById(departId);
        if(executedDepart.getChildrenIds() == null ){
            return Result.error("该部门存在下级部门，请在删除所有下级部门后再进行删除");
        }else if (sysUserDepartService.count(new QueryWrapper<SysUserDepart>().eq("depart_id",departId)) > 0){
            return Result.error("该部门中还存在部员，请在删除所有部门成员后再进行删除");
        }
        try {
            this.removeById(departId);
            sysUserDepartService.remove(new QueryWrapper<SysUserDepart>().eq("depart_id",departId));
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("删除错误，请检查该部门是否存在或请再次尝试");
        }

    }

    @Override
    @Transactional
    public Result updateDepart(SysDepart sysDepart) {
        boolean update = this.updateById(sysDepart);
        if (update)
            return Result.success();
        else
            return Result.error("更新失败，请检查后重试");
    }
}
